<?php
set_time_limit(0);
dl("php_sdl.dll");

error_reporting(E_ALL);
set_time_limit(0);

SDL_Init(SDL_INIT_CDROM);

echo "Drives available: ", SDL_CDNumDrives(), "\n";

// Open default CDROM drive if no argument was passed
if(!isset($argv))
	$argv = $_SERVER['argv'];
$argv[1] = isset($argv[1]) ? $argv[1] : 0;

if(!($cdrom = SDL_CDOpen($argv[1])))
	exit;

$status = SDL_CDStatus($cdrom);

switch (@$argv[2]) {
	case 'stop':
		SDL_CDStop($cdrom);
		break;
	case 'pause':
		SDL_CDPause($cdrom);
		break;
	case 'resume':
		SDL_CDResume($cdrom);
		break;
	default:
		if (preg_match('/\d+/', @$argv[2])) {
			echo "Playing track $argv[2]\n";
			if (false == SDL_CDPlayTracks($cdrom, $argv[2], 0, 1, 0)) {
				echo "Can't play track $argv[2], error: " . SDL_GetError() . "\n";
			}
		} else {
			echo "Usage: " . basename($argv[0]) . " <cd-drive> [command|track to play]\n\n";
			echo "\t<cd-drive>    - Number of drive (0, 1, ...)\n";
			echo "\tcommand       - pause\n";
			echo "\t                resume\n";
			echo "\t                stop\n";
			echo "\ttrack to play - 0, 1, ...\n\n";
		}
}

switch ($status) {
	case SDL_CD_TRAYEMPTY:
		$status_str = "tray empty";
		break;
	case SDL_CD_STOPPED:
		$status_str = "stopped";
		break;
	case SDL_CD_PLAYING:
		$status_str = "playing";
		break;
	case SDL_CD_PAUSED:
		$status_str = "paused";
		break;
	case SDL_CD_ERROR:
		$status_str = "error state";
		break;
	default:
		$status_str = "unknown status '$status'";
}

echo "Inspecting drive $argv[1]\n";
echo "Drive status: $status_str\n";

echo "Drive Tracks: {$cdrom['numtracks']}\n";
for ($i = 0; $i < $cdrom['numtracks']; $i++) {
	list($m, $s, $f) = SDL_Frames_To_MSF($cdrom['track'][$i]['length']);
	if ($f > 0) {
		$s++;
	}
	echo "Track (index $i) {$cdrom['track'][$i]['id']} $m:$s\n";
}

if ($status >= SDL_CD_PLAYING) {
	$m = $s = $f = 0;
	list($m, $s, $f) = SDL_Frames_To_MSF($cdrom['cur_frame']);
	printf("Currently playing track {$cdrom['track'][$cdrom['cur_track']]['id']}, $m:%2.2d\n", $s);
}

?>
